import { useUserStore } from '@st/modules/login/stores/user'

const permissionFlg = import.meta.env.VITE_APP_PLUGINS.includes('permission')

const formatterMenus = (target: any[], origin: any[]) => {
  origin.forEach((item: any, index: number) => {
    target[index] = {
      path: item.menuUrl,
      name: item.routeName,
      component: item.menuComponent,
      redirect: item.menuRedirect,
      meta: { title: item.menuName, icon: item.menuIcon || 'home' },
      children: []
    }
    if (item.children?.length) {
      formatterMenus(target[index].children, item.children)
    }
  })
}

const flatterMenus = (target: any[], origin: any[]) => {
  origin.forEach((item: any, index: number) => {
    if (item.menuComponent === '#') {
      // nav导航级
      target[index] = {
        path: item.menuUrl,
        name: item.routeName,
        component: item.menuComponent,
        redirect: item.menuRedirect,
        meta: { title: item.menuName, icon: item.menuIcon || 'home' },
        children: []
      }
      if (item.children?.length) {
        flatterMenus(target[index].children, item.children)
      }
    } else {
      // sider菜单级
      if (!item.children?.length) {
        // 叶子节点
        target.push({
          path: item.menuUrl,
          name: item.routeName,
          component: item.menuComponent,
          redirect: item.menuRedirect,
          meta: { title: item.menuName, icon: item.menuIcon || 'home' },
          children: []
        })
      } else {
        // 非叶子节点
        flatterMenus(target, item.children)
      }
    }
  })
}

const checkButtonExists = (name: string) => {
  if (permissionFlg) {
    const userStore = useUserStore()
    const buttons = userStore.userInfo.buttons
    let hasPremission = false
    buttons.forEach((v: any) => {
      if (v.routeName === name) {
        hasPremission = true
      }
    })
    return hasPremission
  }
  return true
}

export { formatterMenus, flatterMenus, checkButtonExists }
